using System;
using System.IO;
using System.Collections.Generic;

namespace Hymans.Charles.JAudit
{
	public class Program
	{
		private TextWriter outputStream;
		private List<string> files;
		
		public static void Main (string[] args)
		{
			Program program = new Program(args);
			program.Run();
		}

		public Program(string[] args): this(args, System.Console.Out)
		{
		}
		
		public Program(string[] args, TextWriter outputStream)
		{
			this.outputStream = outputStream;
			// TODO: handle arguments correctly: case with multiple arguments => make a test
			this.files = new List<string>();
			this.CollectFiles(args[0]);
		}
		
		private void CollectFiles(string path)
		{
			if (!Directory.Exists(path))
			{
				FileInfo file = new FileInfo(path);
				// TODO: think about files with extension in upper case? is it possible?
				if (file.Extension.Equals(".java")) this.files.Add(path);
				return;
			}
			foreach (string javaFile in Directory.GetFiles(path))
			{
				this.CollectFiles(javaFile);
			}
			foreach(string directory in Directory.GetDirectories(path))
			{
				this.CollectFiles(directory);
			}
		}
		
		public void Run()
		{
			foreach (string javaFile in this.files)
			{
				// TODO: not really nice to have the fullname, should have the name as given as an argument
				// or relative to the directory given as argument
				this.outputStream.WriteLine("Parsing: " + javaFile);

				using (FileStream stream = new FileStream(javaFile, FileMode.Open))
				{
					Analysis analysis = new Analysis(stream);
					List<Warning> warnings = analysis.Perform();
					foreach (Warning message in warnings)
					{
						this.outputStream.WriteLine(message);
					}
				}
			}
		}
	}
}
